const path = require("path")
const merge = require("webpack-merge")
const common = require("./webpack.common")("production")
const CopyWebpackPlugin = require("copy-webpack-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin")
const TerserPlugin = require("terser-webpack-plugin")
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin

const smp = new SpeedMeasurePlugin()

module.exports = () => {
  const config = merge(common, {
    mode: "production",
    stats: "none",
    output: {
      path: path.join(__dirname, "dist"),
      filename: "[name].js?v=[contenthash:8]"
    },
    optimization: {
      sideEffects: true,
      usedExports: true,
      splitChunks: {
        chunks: "all"
      },
      minimize: true,
      minimizer: [new TerserPlugin(), new OptimizeCssAssetsPlugin()]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new CopyWebpackPlugin({
        patterns: ["public/favicon.ico"]
      })
    ]
  })

  const argv = process.argv

  if (argv.includes("--analyzer")) {
    config.plugins.push(new BundleAnalyzerPlugin())
  }

  if (argv.includes("--speed")) {
    return smp.wrap(config)
  } else {
    return config
  }
}
